package com.yzl.nacos.user.common.enums;

import javax.servlet.http.HttpServletResponse;

import com.yzl.nacos.user.common.entity.ErrorCode;
import com.yzl.nacos.user.common.exception.UnknownEnumException;

/**
 * 业务异常枚举
 *
 * @author Caratacus
 */
public enum ErrorCodeEnum {

	/**
	 * 400
	 */
	BAD_REQUEST(HttpServletResponse.SC_BAD_REQUEST, "请求参数有误"),
	/**
	 * JSON格式错误
	 */
	JSON_FORMAT_ERROR(HttpServletResponse.SC_BAD_REQUEST, "JSON格式错误"),
	/**
	 * 401
	 */
	UNAUTHORIZED(HttpServletResponse.SC_UNAUTHORIZED, "请先进行认证"),
	/**
	 * 403
	 */
	FORBIDDEN(HttpServletResponse.SC_FORBIDDEN, "暂无权操作，如需授权，请联系管理员"),
	/**
	 * 404
	 */
	NOT_FOUND(HttpServletResponse.SC_NOT_FOUND, "未找到"),
	/**
	 * 405
	 */
	METHOD_NOT_ALLOWED(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "请求方式不支持"),
	/**
	 * 406
	 */
	NOT_ACCEPTABLE(HttpServletResponse.SC_NOT_ACCEPTABLE, "不可接受该请求"),
	/**
	 * 411
	 */
	LENGTH_REQUIRED(HttpServletResponse.SC_LENGTH_REQUIRED, "请求长度受限制"),
	/**
	 * 415
	 */
	UNSUPPORTED_MEDIA_TYPE(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "该请求不支持的媒体类型"),
	/**
	 * 416
	 */
	REQUESTED_RANGE_NOT_SATISFIABLE(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "该请求不在请求满足的范围"),
	/**
	 * 500
	 */
	INTERNAL_SERVER_ERROR(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器出了点问题，抱歉"),
	/**
	 * 503
	 */
	SERVICE_UNAVAILABLE(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "请求超时"),
	/**
	 * 消息异常
	 */
	MSG_EXCEPTION(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "默认消息异常");

	private final int code;
	private final String msg;

	ErrorCodeEnum(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}

	/**
	 * 转换为ErrorCode(自定义返回消息)
	 *
	 * @param msg
	 * @return
	 */
	public ErrorCode overrideMsg(String msg) {
		return ErrorCode.builder().status(getCode()).error(name()).msg(msg).build();
	}

	/**
	 * 转换为ErrorCode
	 *
	 * @return
	 */
	public ErrorCode convert() {
		return ErrorCode.builder().status(getCode()).error(name()).msg(getMsg()).build();
	}

	public static ErrorCodeEnum getErrorCode(String errorCode) {
		ErrorCodeEnum[] enums = ErrorCodeEnum.values();
		for (ErrorCodeEnum errorCodeEnum : enums) {
			if (errorCodeEnum.name().equalsIgnoreCase(errorCode)) {
				return errorCodeEnum;
			}
		}
		throw new UnknownEnumException("Error: Unknown errorCode, or do not support changing errorCode!\n");
	}


	public int getCode() {
		return this.code;
	}

	public String getMsg() {
		return this.msg;
	}

}